from selenium.webdriver import Firefox
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.firefox.options import Options as FOptions
from selenium.webdriver.support.ui import WebDriverWait

from tools.express.com import *


# 创建一个模拟手动点击浏览器的爬虫，支持浏览器: 火狐
def build_spider(data, url) -> Firefox:
    if not url:
        raise AttributeError('未传入URL')
    return build_browser(url)


# 创建一个模拟手动点击，但是不显示浏览器窗口的爬虫，支持浏览器：火狐
def build_hidden_spider(data, url) -> Firefox:
    if not url:
        raise AttributeError('未传入URL')
    op = FOptions()
    op.add_argument('-headless')
    return build_browser(url, op)


# 点击一个网页元素，传入css选择器表达式，支持不可点击时五秒等待
def click_ele(data: Firefox, css_selector) -> Firefox:
    wait = WebDriverWait(data, 5)
    wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, css_selector))).click()
    return data


# 在网页中的输入框输入指定数据，参数： css选择器表达式、输入值
def input_ele(data: Firefox, params: str) -> Firefox:
    a_tuple = tuple(eval(params))
    wait = WebDriverWait(data, 5)
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, a_tuple[0]))).send_keys(a_tuple[1])
    return data


# 切换到指定标签页,默认切换到第二页
def switch_page(data: Firefox, param='1') -> Firefox:
    page = int(param)
    data.switch_to_window(data.window_handles[page])
    print('页数', data.window_handles)
    return data


# 将网页中的列表信息，分多字段输出成json文件:格式：{content:[{p1:'',p2:'',...},...], count:0}。 传入的参数有：列表选择器表达式, 列表下的（字段1，选择器1），（字段2，选择器2），...
def output_table_to_json(data: Firefox, param) -> Firefox:
    params = tuple(eval(param))
    res = dict()
    tb_data = list()
    for col in data.find_elements_by_css_selector(params[0]):
        row = dict()
        for x in range(1, len(params)):
            p = col.find_element_by_css_selector(params[x][1])
            row[params[x][0]] = p.text
        tb_data.append(row)
    res['content'] = tb_data
    res['count'] = len(tb_data)
    write_json_to_file('out/output_web_%s.json' % time.strftime('%Y-%m-%d_%H-%M-%S'), res)
    return data


# 打印当前窗口标题
def print_title(data: Firefox) ->Firefox:
    print(data.title)
    return data


# 关闭所有窗口
def close(data: Firefox):
    data.quit()
    return None


def build_browser(url, options=FOptions()) -> Firefox:
    browser = Firefox(executable_path='E:\webdriver\geckodriver.exe', firefox_options=options)
    browser.get(url)
    return browser

